<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <label for="">用户名:</label>
    <input type="text" id="name" autocomplete="off">
    <span class="inf"></span><br>
    <label for="">密码:</label>
    <input type="password" id="psw">
    <span class="inf"></span><br>
    <input type="button" value="注册">
</body>
<script>
    (function () {
        let name = document.querySelector('#name');
        let inf = document.querySelectorAll('.inf');
        let psw = document.querySelector('#psw');

        name.onblur = () => {
            let val = name.value.trim();
            if (val) {
                //通过ajax检测数据
                let xhr = new XMLHttpRequest();
                //1号线：
                let data = 'name=' + val;
                xhr.open('get', 'api/02form.php?' + data, true);
                //2号线:
                xhr.send(null);
                //3号线：跑到PHP文件中做数据
                //4号线：接受回来得数据在页面做渲染：
                xhr.onreadystatechange = () => {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        console.log(xhr.responseText);
                        let res = xhr.responseText;
                        if (res == '0') {
                            //不可以注册
                            inf[0].innerHTML = '该用户太受欢迎啦，请换一个';
                            inf[0].style.color = 'red';
                        } else {
                            //可以注册
                            inf[0].innerHTML = '验证通过';
                            inf[0].style.color = '#58bc58';
                        }
                    }
                }
            } else {
                inf[0].innerHTML = '请输入用户名';
                inf[0].style.color = 'red';
            }
        }

        //密码验证：
        psw.onblur = () => {
            let mima = psw.value.trim();
            if (mima) {
                var reg = /^\S{6,20}$/;
                var res = reg.test(mima);
                if (res) {
                    //console.log(res);
                    inf[1].innerHTML = '验证通过';
                    inf[1].style.color = 'green';
                } else {
                    inf[1].innerHTML = '验证不通过';
                    inf[1].style.color = 'red';
                }
            } else {
                inf[1].innerHTML = '请输入密码';
                inf[1].style.color = 'red';
            }
        }
        

    })();
</script>

</html>